import { ITestAgentClient, GenerateTestRequest, TestCaseResponse } from "../interface.js";
import { getHeaders } from "./headers.js";

export class TestAgentClient implements ITestAgentClient {
  constructor(
    private readonly serverUrl: string,
    private readonly userToken?: string,
  ) {}

  async getConfig(): Promise<any> {
    const response = await fetch(`${this.serverUrl}/config`, {
      method: "GET",
      headers: getHeaders(this.userToken),
    });

    if (!response.ok) {
      throw new Error(`Failed to fetch config (${response.status})`);
    }
    return await response.json();
  }

  async generateTest(req: GenerateTestRequest): Promise<TestCaseResponse> {
    const response = await fetch(`${this.serverUrl}/generateTest`, {
      method: "POST",
      headers: getHeaders(this.userToken),
      body: JSON.stringify(req),
    });

    if (!response.ok) {
      const msg = await response.text();
      throw new Error(`Test generation failed (${response.status}): ${msg}`);
    }

    return await response.json();
  }

  async sendFeedback(testId: string, feedback: string): Promise<void> {
    const response = await fetch(`${this.serverUrl}/feedback`, {
      method: "POST",
      headers: getHeaders(this.userToken),
      body: JSON.stringify({ testId, feedback }),
    });

    if (!response.ok) {
      console.warn(`Failed to send feedback (${response.status})`);
    }
  }
}